package com.lw.lost.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.MomentAdapter
import com.lw.lost.databinding.FragmentMomentsBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.Moment
import com.lw.lost.utils.PreferenceUtils

class MomentsFragment : Fragment() {

    private var _binding: FragmentMomentsBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: DBlost
    private lateinit var momentAdapter: MomentAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMomentsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        db = DBlost(requireContext())
        
        setupRecyclerView()
        setupSwipeRefresh()
        loadMoments()
    }

    private fun setupRecyclerView() {
        momentAdapter = MomentAdapter(
            onLikeClick = { moment -> handleLike(moment) },
            onCommentClick = { moment -> handleComment(moment) },
            currentUserId = PreferenceUtils.getUserId(requireContext()),
            db = db
        )
        
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = momentAdapter
        }
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefresh.setOnRefreshListener {
            loadMoments()
        }
    }

    private fun loadMoments() {
        val cursor = db.postDao.getAllPosts()
        val moments = mutableListOf<Moment>()

        cursor.use { cursor ->
            while (cursor.moveToNext()) {
                moments.add(
                    Moment(
                        postId = cursor.getLong(cursor.getColumnIndexOrThrow("postId")),
                        userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                        userName = cursor.getString(cursor.getColumnIndexOrThrow("userName")),
                        userAvatar = cursor.getString(cursor.getColumnIndexOrThrow("userAvatar")),
                        content = cursor.getString(cursor.getColumnIndexOrThrow("content")),
                        imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("imageUrl")),
                        createTime = cursor.getString(cursor.getColumnIndexOrThrow("createTime")),
                        likeCount = cursor.getInt(cursor.getColumnIndexOrThrow("likeCount")),
                        commentCount = cursor.getInt(cursor.getColumnIndexOrThrow("commentCount"))
                    )
                )
            }
        }

        momentAdapter.submitList(moments)
        binding.swipeRefresh.isRefreshing = false
    }

    private fun handleLike(moment: Moment) {
        val currentUserId = PreferenceUtils.getUserId(requireContext())
        val isLiked = db.postDao.isLikedByUser(moment.postId, currentUserId)
        
        val success = if (isLiked) {
            db.postDao.unlike(moment.postId, currentUserId)
        } else {
            db.postDao.like(moment.postId, currentUserId)
        }
        
        if (success) {
            loadMoments() // 重新加载数据以更新UI
            val message = if (isLiked) "已取消点赞" else "点赞成功"
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        } else {
            val message = if (isLiked) "取消失败" else "已经点赞过了"
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        }
    }

    private fun handleComment(moment: Moment) {
        // 可以在这里处理评论点击事件，比如显示软键盘等
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 